package com.zimug.dongbb.server.jwt.system.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zimug.commons.exception.CustomException;
import com.zimug.commons.exception.CustomExceptionType;
import com.zimug.dongbb.persistence.system.mapper.MySystemMapper;
import com.zimug.dongbb.persistence.system.mapper.SysUserMapper;
import com.zimug.dongbb.persistence.system.model.SysUser;
import com.zimug.dongbb.persistence.system.model.SysUserOrg;
import com.zimug.dongbb.server.jwt.config.DbLoadSysConfig;
import org.apache.commons.lang.StringUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class SysuserService {

    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private MySystemMapper mySystemMapper;
    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private DbLoadSysConfig dbLoadSysConfig;

    public SysUser getUserByUserName(String userName){
        if(StringUtils.isNotEmpty(userName)){
            /*SysUserExample sysUserExample = new SysUserExample();
            sysUserExample.createCriteria().andUsernameEqualTo(userName);

            List<SysUser> querys =
              sysUserMapper.selectByExample(sysUserExample);


            if(querys.size() > 0){
              //因为数据需要返回给前端，所以置空密码
              querys.get(0).setPassword("");
            }
            return querys.size() > 0 ? querys.get(0):null;*/

          SysUser sysUser = sysUserMapper.selectOne(
            new QueryWrapper<SysUser>().eq("username",userName));
          if(sysUser != null){
            sysUser.setPassword("");
          }
          return sysUser;
        }else{
            throw new CustomException(CustomExceptionType.USER_INPUT_ERROR,
                    "查询参数用户名不存在");
        }
    }

    public Page<SysUserOrg> queryUser(Long orgId ,
                                          String username ,
                                          String phone,
                                          String email,
                                          Boolean enabled,
                                          Date createStartTime,
                                          Date createEndTime,
                                          Integer pageNum,
                                          Integer pageSize){
      //PageHelper.startPage(pageNum, pageSize);
      Page<SysUserOrg> page = new Page<> (pageNum,pageSize);   //查询第1页，每页10条数据
      List<SysUserOrg> sysUserOrgs =  mySystemMapper.selectUser(orgId,username,phone,email,enabled,
                                    createStartTime,
                                    createEndTime);
      page.setRecords(sysUserOrgs);
      return page;

    }


  public void updateUser(SysUser sysuser){
    if(sysuser.getId() == null){
      throw new CustomException(CustomExceptionType.USER_INPUT_ERROR,
        "修改操作必须带主键");
    }else{
      sysUserMapper.updateById(sysuser);
    }
  }

  public void addUser(SysUser sysuser){
    sysuser.setPassword(passwordEncoder.encode(
      dbLoadSysConfig.getConfigItem("user.init.password")
    ));
    sysuser.setCreateTime(new Date());  //创建时间
    sysuser.setEnabled(true); //新增用户激活
    sysUserMapper.insert(sysuser);
  }

  public void deleteUser(Long userId){
    sysUserMapper.deleteById(userId);
  }

  public void pwdreset(Long userId){
    if(userId == null){
      throw new CustomException(CustomExceptionType.USER_INPUT_ERROR,
        "重置密码必须带主键");
    }else{
      SysUser sysUser = new SysUser();
      sysUser.setId(userId);

      sysUser.setPassword(passwordEncoder.encode(
        dbLoadSysConfig.getConfigItem("user.init.password")
      ));

      sysUserMapper.updateById(sysUser);
    }
  }

  public Boolean isdefault(String username){
    /*SysUserExample sysUserExample = new SysUserExample();
    sysUserExample.createCriteria().andUsernameEqualTo(username);
    List<SysUser> sysUsers = sysUserMapper.selectByExample(sysUserExample);*/

    SysUser sysUser = sysUserMapper.selectOne(
      new QueryWrapper<SysUser>().eq("username",username));


    //判断数据库密码是否是默认密码
    return passwordEncoder.matches(
      dbLoadSysConfig.getConfigItem("user.init.password"),
      sysUser.getPassword());
  }

  public void changePwd(String username,String oldPass,String newPass){
    /*SysUserExample sysUserExample = new SysUserExample();
    sysUserExample.createCriteria().andUsernameEqualTo(username);
    List<SysUser> sysUsers = sysUserMapper.selectByExample(sysUserExample);*/

    SysUser sysUser = sysUserMapper.selectOne(
      new QueryWrapper<SysUser>().eq("username",username));
    //判断旧密码是否正确
    boolean isMatch = passwordEncoder.matches(oldPass,sysUser.getPassword());

    if(isMatch){
      SysUser sysUserNew = new SysUser();
      sysUserNew.setId(sysUser.getId());
      sysUserNew.setPassword(passwordEncoder.encode(newPass));
      sysUserMapper.updateById(sysUserNew);
    }else{
      throw new CustomException(CustomExceptionType.USER_INPUT_ERROR,
        "原密码输入错误，请确认后重新输入！");
    }

  }

}
